#include "taskmanager.h"
#include "task.h"
#include "xmpptask.h"
#include "constants.h"

namespace tinkle {

TaskManager::TaskManager(StanzaManager *stanzaMgr)
    : BaseTask(this),
      _stanzaMgr(stanzaMgr) {
    _stanzaMgr->SigRead.connect(this, &TaskManager::OnStanzaRead);
}

TaskManager::~TaskManager() {

}

void TaskManager::StartTask(Task *task) {
    _taskQ.push_back(task);
    RunTasks();
}

void TaskManager::AbortTask(Task *task) {
    // TODO: implement this function
    // Note! this function didn't implement yet
}


void TaskManager::Handle() {

}

void TaskManager::Handle(XmlNode *stanza) {
    bool stanzaHandled = false;
    printf ("task size:%d\n\n", _taskQ.size());
    for (size_t i = 0; i < _taskQ.size(); ++i) {
        if (_taskQ[i]->HasNetworkEvent() &&
            dynamic_cast<XmppTask *>(_taskQ[i])->NextStanza(stanza)) {
            stanzaHandled = true;
            // have the task run
            _taskQ[i]->Process();
            // delete the stanza
            delete stanza;
            break;
        }
    }
    if (!stanzaHandled) {
        printf ("TaskManager should have a default task in handle method\n");
    }
}

StanzaManager *TaskManager::GetStanzaManager() const {
    return _stanzaMgr;
}

void TaskManager::RunTasks() {
    for (size_t i = 0; i < _taskQ.size(); ++i) {
        if (!_taskQ[i]->IsDone()) {
            _taskQ[i]->Process();
        }
    }
}

void TaskManager::OnStanzaRead(StanzaManager *stanzaMgr) {
    // when a new stanza is received and ready to be used, handle it!
    Handle(stanzaMgr->Read());
}

}